<?php

session_start();

header('Content-Type: application/json');

class MyDB extends SQLite3 {
	function __construct() {
		$this->open('access.db');
	}
}

$db = new MyDB();

if(!$db) { 
		echo $db->lastErrorMsg();
}

$json = array();

$delete_sql = "DELETE FROM ACCESS_".$_SESSION["uid"]." WHERE id = (SELECT MAX(id) FROM ACCESS_".$_SESSION["uid"].");";
$time = time() + 1;
$date = date('Y-m-d H:i:s', $time - 5); // -5 bo jak roznica miedzy czasem na komputerze zbyt mala to NaN...
$sql_new = "INSERT INTO ACCESS_".$_SESSION["uid"]." (date) VALUES ('$date');";

if($_POST["status"] == "pracuje") {
	$results = $db->query($sql_new);
	echo json_encode("nie pracuje");
} else {
	$last_entry = "SELECT date FROM ACCESS_".$_SESSION["uid"]." WHERE id = (SELECT MAX(id) FROM ACCESS_".$_SESSION["uid"].");";
	$results = $db->query($last_entry);
	while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
		$last_date = $row['date'];
	}
	$parse_sql = explode(" ", $last_date);
	$parse_date = explode(" ", $date);
	if($parse_sql[0] != $parse_date[0]) {
		$results = $db->query($sql_new);
	} else {
		$results = $db->query($delete_sql);
	}
	echo json_encode("pracuje");
}

$db->close();

?>